#include <stdio.h>
#include <string.h>


static unsigned char bin2ascii(unsigned char in) {
    if (in >= 0 && in <= 9) {
        return in + '0';
    } else if (in >= 0xa && in <= 0xf) {
        return in - 0x0a + 'A';
    } else {
        return 0;
    }
}


static unsigned char ascii2bin(unsigned char in) {
    if (in >= '0' && in <= '9') {
        return in - '0';
    } else if (in >= 'a' && in <= 'f') {
        return in - 'a' + 0x0a;
    } else if (in >= 'A' && in <= 'F') {
        return in - 'A' + 0x0a;
    } else {
        return 0;
    }
}


void hexlify(unsigned char *to, unsigned char *from, unsigned int length) {
	int index = 0;
	for (int i = 0; i < length; i++) {
		to[index] = bin2ascii((from[i] & 0xF0) >> 4);
		to[index+1] = bin2ascii(from[i] & 0x0F);
		index += 2;
	}
}


void unhexlify(unsigned char *to, unsigned char *from, unsigned int length) {
	int index = 0;
	for (int i = 0; i < length; i += 2) {
		to[index++] = (ascii2bin(from[i]) << 4) | ascii2bin(from[i+1]);
	}
}
